﻿using System;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace Common
{
    public class SendEmailHelper
    {
         #region 静态方法发送
        public static void Send(string to, string cc, string subject, string body, string attachments, bool sync)
        {
            try
            {
                MailMessage mailMsg = new MailMessage { From = new MailAddress("dataservice@edoctor.cn", "eDoctor") };
                foreach (var s in to.Replace("；", ";").Replace(",", ";").Replace("，", ";").Split(';'))
                {
                    mailMsg.To.Add(new MailAddress(s));
                }

                if (!string.IsNullOrEmpty(cc))
                {
                    foreach (var s in cc.Replace("；", ";").Replace(",", ";").Replace("，", ";").Split(';'))
                    {
                        mailMsg.CC.Add(new MailAddress(s));
                    }
                }
                mailMsg.Subject = subject;
                mailMsg.SubjectEncoding = Encoding.UTF8;
                mailMsg.IsBodyHtml = true;
                mailMsg.BodyEncoding = Encoding.UTF8;
                mailMsg.Body = body;
                mailMsg.Priority = MailPriority.Normal;

                if (!string.IsNullOrWhiteSpace(attachments))
                {
                    var attachsArr = attachments.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    if (attachsArr.Length > 0)
                    {
                        foreach (var attachitem in attachsArr)
                        {
                            var fileName = HttpUtility.UrlEncode(attachitem.Replace("\\", "/"), Encoding.UTF8);
                            mailMsg.Attachments.Add(new Attachment(attachitem.Replace("\\", "/")) { NameEncoding = Encoding.UTF8 });
                        }
                    }
                    else
                    {
                        mailMsg.Attachments.Add(new Attachment(attachments));
                    }
                }

                SmtpClient sender = new SmtpClient();
                sender.Host = "smtp.partner.outlook.cn";
                sender.Port = 587;
                sender.UseDefaultCredentials = false;
                sender.Credentials = new NetworkCredential("dataservice@edoctor.cn", "Sh51699890");
                sender.DeliveryMethod = SmtpDeliveryMethod.Network;
                sender.EnableSsl = true;

                if (sync)
                {
                    //异步发送
                    sender.SendCompleted += new SendCompletedEventHandler(static_client_SendCompleted);
                    sender.SendAsync(mailMsg, "this is a message param");
                }
                else
                {
                    //同步发送
                    sender.Send(mailMsg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
                Console.ReadLine();
            }
        }

        private static void static_client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //e.UserState 自定义参数
            MailMessage mail = e.UserState as MailMessage;

            string token = (string)e.UserState;
            if (e.Cancelled)
            {
                Logs.Execute(string.Format("{0} Send canceled.", token));
            }

            if (e.Error != null)
            {
                Logs.Execute(string.Format("error:[{0}] {1}", token, e.Error));
            }
            else
            {
                Logs.Execute("Message sent");
            }
        }

        internal static string ReplaceChar(string str)
        {
            return str.Replace("&", "{SpecialChar}");
        }
        #endregion

        #region 实例化发送

        readonly string _smtp;
        readonly string _from;
        readonly string _password;
        readonly int _port;

        /// <summary>
        /// 使用office365邮箱
        /// </summary>
        public SendEmailHelper()
            : this("smtp.partner.outlook.cn", "dataservice@edoctor.cn", "Sh51699890", 587)
        {

        }

        /// <summary>
        /// 读取配置初始化
        /// </summary>
        /// <param name="smtp"></param>
        /// <param name="from"></param>
        /// <param name="password"></param>
        /// <param name="port"></param>
        public SendEmailHelper(string smtp, string from, string password, int port)
        {
            _smtp = smtp; _from = from; _password = password; _port = port;
        }

        private void SendMail(string to, string cc, string subject, string body, string attachments, bool sync)
        {
            try
            {
                MailMessage mailMsg = new MailMessage { From = new MailAddress(_from, "eDoctor") };
                foreach (var s in to.Replace("；", ";").Replace(",", ";").Replace("，", ";").Split(';'))
                {
                    mailMsg.To.Add(new MailAddress(s));
                }

                if (!string.IsNullOrEmpty(cc))
                {
                    foreach (var s in cc.Replace("；", ";").Replace(",", ";").Replace("，", ";").Split(';'))
                    {
                        mailMsg.CC.Add(new MailAddress(s));
                    }
                }
                mailMsg.Subject = subject;
                mailMsg.SubjectEncoding = Encoding.UTF8;
                mailMsg.IsBodyHtml = true;
                mailMsg.BodyEncoding = Encoding.UTF8;
                mailMsg.Body = body;
                mailMsg.Priority = MailPriority.Normal;

                if (!string.IsNullOrWhiteSpace(attachments))
                {
                    var attachsArr = attachments.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    if (attachsArr.Length > 0)
                    {
                        foreach (var attachitem in attachsArr)
                        {
                            var fileName = HttpUtility.UrlEncode(attachitem.Replace("\\", "/"), Encoding.UTF8);
                            mailMsg.Attachments.Add(new Attachment(attachitem.Replace("\\", "/")) { NameEncoding = Encoding.UTF8 });
                        }
                    }
                    else
                    {
                        mailMsg.Attachments.Add(new Attachment(attachments));
                    }
                }

                SmtpClient sender = new SmtpClient();
                sender.Host = this._smtp;
                sender.Port = this._port;
                sender.UseDefaultCredentials = false;
                sender.Credentials = new NetworkCredential(this._from, this._password);
                sender.DeliveryMethod = SmtpDeliveryMethod.Network;
                sender.EnableSsl = true;

                if (sync)
                {
                    //异步发送
                    sender.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                    sender.SendAsync(mailMsg, "this is a message param");
                }
                else
                {
                    //同步发送
                    sender.Send(mailMsg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
                Console.ReadLine();
            }
        }

        public void Send(string to, string cc, string subject, string body)
        {
            Send(to, cc, subject, body, null);
        }

        public void Send(string to, string cc, string subject, string body, string attachments)
        {
            SendMail(to, cc, subject, body, attachments, false);
        }

        public void SendAsync(string to, string cc, string subject, string body)
        {
            SendAsync(to, cc, subject, body, null);
        }

        public void SendAsync(string to, string cc, string subject, string body, string attachments)
        {
            SendMail(to, cc, subject, body, attachments, true);
        }

        private void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //e.UserState 自定义参数
            MailMessage mail = e.UserState as MailMessage;

            string token = (string)e.UserState;
            if (e.Cancelled)
            {
                Logs.Execute(string.Format("{0} Send canceled.", token));
            }

            if (e.Error != null)
            {
                Logs.Execute(string.Format("error:[{0}] {1}", token, e.Error));
            }
            else
            {
                Logs.Execute("Message sent");
            }
        }

        #endregion
    }
}
